package com.sf.gis.boot.rcboot.jwt;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.interfaces.Claim;
import com.google.gson.Gson;
import com.sf.gis.boot.rcboot.util.JsonResponse;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 80004819
 * @ClassName:
 * @Description:
 * @date 2020年09月11日 17:34:49
 */
@Slf4j
//@WebFilter(filterName = "JwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter {

    private static final Gson GSON = new Gson();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        //设置编码格式
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        //获取 header里的token
        final String token = request.getHeader("authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        // Except OPTIONS, other request should be checked by JWT
        else {

            String requestURI = request.getRequestURI();
            if (isPass(requestURI)) {
                chain.doFilter(req, res);
                return;
            }

            if (token == null) {
                response.getWriter().write(GSON.toJson(JsonResponse.error("没有token")));
                return;
            }
            //如果获取到了token，验证token是否合法
            Map<String, Claim> userData = JwtUtil.verifyToken(token);
            if (userData == null) {
                response.getWriter().write(GSON.toJson(JsonResponse.error("token不合法！")));
                return;
            }
            String userName = userData.get("userName").asString();
            String password = userData.get("password").asString();
            //拦截器 拿到用户信息，放到request中
//            request.setAttribute("userName", userName);
//            request.setAttribute("password", password);
            chain.doFilter(req, res);
        }
    }

    /**
     * 直接通行的uri
     *
     * @param requestURI
     * @return
     */
    private boolean isPass(String requestURI) {
        return StrUtil.equals(requestURI, "/") || StrUtil.startWithIgnoreCase(requestURI, "/jwt/getToken") ||
                StrUtil.startWithIgnoreCase(requestURI, "/swagger-ui.html") ||
                StrUtil.startWithIgnoreCase(requestURI, "/error")
                || StrUtil.startWithIgnoreCase(requestURI, "/csrf")
                || StrUtil.containsAnyIgnoreCase(requestURI, "v2/api-docs", "swagger");
    }

    @Override
    public void destroy() {
    }
}
